<template>
  <div class="singer" ref="singer">
    <list-view :data="artist" @select="selectSinger" ref="list"></list-view>
    <router-view></router-view>
  </div>
</template>

<script>
  import {
    getSingerList
  } from "api/singer.js";
  import ListView from "base/listview/ListView";
  import {
    mapMutations
  } from "vuex";
  import axios from "axios";
  import Mock from 'mockjs';
  import {playlistMixin} from 'common/js/mixin';

  const hotName = "热门";
  const hotSingerLength = 10;
  export default {
    name: "Singer",
    mixins:[playlistMixin],
    data() {
      return {
        artist: []
      };
    },
    methods: {
      getData() {
        getSingerList().then(res => {
          this.artist = this.normalList(res.singerList.data.singerlist);
        });
      },
      normalList(list) {
        // 添加随机字母
        const lists = []
        for (let i = 0; i < list.length; i++) {
          list[i].firstchar = Mock.mock('@string("upper", 1)')
          lists.push(list[i])
        }
        // 添加随机字母 结束
        let map = {
          hot: {
            title: hotName,
            items: []
          }
        };
        lists.forEach((item, index) => {
          if (index < hotSingerLength) {
            map.hot.items.push({
              name: item.singer_name,
              id: item.singer_id,
              imgUrl: item.singer_pic,
              singer_mid: item.singer_mid
            });
          }
          const key = item.firstchar;
          if (!map[key]) {
            map[key] = {
              title: key,
              items: []
            };
          }
          map[key].items.push({
            name: item.singer_name,
            id: item.singer_id,
            imgUrl: item.singer_pic,
            singer_mid: item.singer_mid
          });
        });
        // 为了等到有序列表
        let hot = [];
        let ret = [];
        for (let key in map) {
          let val = map[key];
          if (val.title.match(/[a-zA-Z]/)) {
            ret.push(val);
          } else if (val.title === hotName) {
            hot.push(val);
          }
        }
        ret.sort((a, b) => {
          return a.title.charCodeAt(0) - b.title.charCodeAt(0);
        });
        return hot.concat(ret);
      },
      selectSinger(item) {
        this.$router.push({
          path: `/singer/${item.singer_mid}`
        });
        this.setSinger(item);
      },
      handlePlayList(playList){
        const bottom = playList.length > 0 ? '60px' : ''
        this.$refs.singer.style.bottom = bottom
        this.$refs.list.refresh()
      },
      ...mapMutations({
        setSinger: "SET_SINGER"
      })
    },
    components: {
      ListView
    },
    created() {
      this.getData();
    }
  };

</script>
